import 'error_code.dart';
import 'http_exception.dart';
import 'package:dio/dio.dart';
import 'response_data.dart';

/// 解析response结构体拦截器, 强制所有服务器返回的格式都这样
class ResponseInterceptor extends Interceptor {
  @override
  void onResponse(
    Response response,
    ResponseInterceptorHandler handler,
  ) {
    if (ResponseType.json != response.requestOptions.responseType)
      return handler.next(response);
    dynamic oldData = response.data;
    ResponseData data;

    /// 校验服务器端数据格式
    if (oldData != null && oldData is String) {
      throw HttpException(
        code: ErrorCode.SERVER_ERROR.code,
        msg:
            "服务器端返回数据异常, 返回数据为: $oldData, 请求uri: ${response.requestOptions.uri}",
      );
    }

    /// 解决后端返回数据不是标准`{'code': code, 'msg': msg, 'data': data}`格式时,封装成标准格式返回
    if (oldData == null ||
        (oldData['code'] == null && oldData['msg'] == null)) {
      data = ResponseData(
        code: ErrorCode.SUCCESS.code,
        msg: ErrorCode.SUCCESS.msg,
        data: oldData,
      );
    } else {
      data = ResponseData(
        code: oldData['code'] ?? ErrorCode.SUCCESS.code,
        msg: oldData['msg'] ??
            (oldData['code'] != null &&
                    oldData['code'] == ErrorCode.SUCCESS.code
                ? ErrorCode.SUCCESS.msg
                : ErrorCode.SERVER_ERROR.msg),
        data: oldData['data'],
      );
    }
    response.data = data;

    /// 将响应code不为200的请求进入error
    if (data.code != ErrorCode.SUCCESS.code) {
      throw HttpException(code: data.code, msg: data.msg, response: response);
    }
    return handler.next(response);
  }
}
